<!-- 登录 -->
<template>
  <div class="Login-root">
    <div class="form-wrap">
      <div class="bg-wrap">
        <img src="../../assets/img/login/bg_right.png" alt="" />
      </div>
      <div class="login-form">
        <div class="title">
          <img src="../../assets/img/login/title.png" alt="" />
        </div>
        <div class="login-tabs">
          <div v-if="tabS === 0">
            <p @click="loginTabs(1)" :class="{ active: activeIndex === 1 }">账号登陆</p>
            <p class="loginTabs2" @click="loginTabs(2)" :class="{ active: activeIndex === 2 }">短信验证</p>
          </div>
          <p v-if="tabS === 1" class="active">重置密码</p>
          <p v-if="tabS === 2" class="activeTabs">注册</p>
        </div>
        <div class="login-tabs-span">{{ tabMessage }}</div>
        
          <div v-if="tabS === 0">
            <template v-if="activeIndex === 1">
              <a-form-model class="form" ref="form" :model="form" :rules="formRules">
                <a-form-model-item label="" prop="account">
                  <a-input  v-model="form.account" placeholder="用户名" allowClear >
                    <a-icon slot="prefix" type="user" />
                  </a-input>
                </a-form-model-item>
                <a-form-model-item  label="" prop="password">
                  <a-input-password
                    @pressEnter="handleLogin"
                    v-model="form.password"
                    placeholder="密码"
                    allowClear
                    visibilityToggle
                  >
                  <a-icon slot="prefix" type="lock" />
                  </a-input-password>
                </a-form-model-item>
            </a-form-model>
            </template>
            <template v-else>
              <a-form-model class="form" ref="form2" :model="form2" :rules="formRules2">
              <a-form-model-item label="" prop="mobile">
                <a-input v-model="form2.mobile" placeholder="手机号" allowClear :maxLength="11" >
                  <a-icon slot="prefix" type="user" />
                </a-input>
              </a-form-model-item>
              <a-form-model-item label="" prop="code">
                <div class="flex">
                  <a-input v-model="form2.code" placeholder="验证码" :maxLength="4" allowClear >
                    <template #prefix>
                      <a-icon type="safety-certificate" />
                    </template>
                  </a-input>
                  <a-button @click="getVerificationCode">
                    {{ countdown > 0 ? `${countdown}秒后重试` : '获取验证码' }}
                  </a-button>
                </div>
              </a-form-model-item>
            </a-form-model>
            </template>
          </div>

          <div v-if="tabS === 1 || tabS === 2">
            <a-form-model class="form" ref="form3" :model="form3" :rules="formRules3">
              <a-form-model-item label="" prop="mobile">
                <a-input v-model="form3.mobile" placeholder="手机号" allowClear :maxLength="11" >
                  <a-icon slot="prefix" type="user" />
                </a-input>
              </a-form-model-item>
              <a-form-model-item label="" prop="code">
                <div class="flex">
                  <a-input v-model="form3.code" placeholder="验证码" :maxLength="4" allowClear >
                    <template #prefix>
                      <a-icon type="safety-certificate" />
                    </template>
                  </a-input>
                  <a-button @click="getVerificationCode2">
                    {{ countdown > 0 ? `${countdown}秒后重试` : '获取验证码' }}
                  </a-button>
                </div>
              </a-form-model-item>
              <a-form-model-item label="" prop="password">
                <a-input-password
                  @pressEnter="handleLogin"
                  v-model="form3.password"
                  placeholder="密码"
                  allowClear
                  visibilityToggle
                >
                <a-icon slot="prefix" type="lock" />
                </a-input-password>
              </a-form-model-item>
            </a-form-model>
          </div>


        <div v-if="tabS === 0 && activeIndex === 1" class="forgot_password">
          <span @click="tabS = 1">忘记密码 ></span>
        </div>
        <div class="agreement">
          <a-checkbox v-model="agreementChecked">我已阅读并遵守 <span>《用户协议》</span> 与 <span>《隐私协议》</span></a-checkbox>
        </div>
        <a-button v-if="tabS === 0" class="login-btn" type="primary" size="large" :loading="btnLoading" block @click="handleLogin">登录</a-button>
        <a-button v-if="tabS === 1" class="login-btn" type="primary" size="large" :loading="btnLoading" block @click="submitConfirmLogin">确定</a-button>
        <a-button v-if="tabS === 2" class="login-btn" type="primary" size="large" :loading="btnLoading" block @click="submitSignIn">注册</a-button>
        <div class="Register_now">
          <span @click="Register_now" v-if="tabS === 0">立即注册></span>
          <span @click="tabS = 0" v-if="tabS !== 0">返回登陆></span>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { mapActions } from "vuex";
import * as Ajax from "@/api/login";
import config from "@/utils/config";
import { SafetyCertificateOutlined } from '@ant-design/icons-vue';
export default {
  name: "Login",
  data() {
    const validateaccount = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请输入手机号"));
      } else if (!this.isValidaccountNumber(value)) {
        callback(new Error("请输入正确格式的手机号"));
      } else {
        callback();
      }
    };
    return {
      defaultTitle: config.title,
      form: {
        account: "",
        password: "",
      },
      form2: {
        mobile: '',
        code: '',
      },
      form3: {
        mobile: '',
        code: '',
        password: '',
      },
      formRules: {
        account: {
          required: true,
          message: "请输入账号",
          trigger: ["blur", "change"],
        },
        password: {
          required: true,
          message: "请输入密码",
          trigger: ["blur", "change"],
        },
        account: {
          required: true,
          validator: validateaccount,
          trigger: ["blur", "change"],
        },
        code: {
          required: true,
          message: "请输入验证码",
          trigger: ["blur", "change"],
        },
      },
      formRules2: {
        mobile: {
          required: true,
          validator: validateaccount,
          trigger: ["blur", "change"],
        },
        code: {
          required: true,
          message: "请输入验证码",
          trigger: ["blur", "change"],
        },
      },
      formRules3: {
        mobile: {
          required: true,
          message: "请输入手机号",
          trigger: ["blur", "change"],
        },
        password: {
          required: true,
          message: "请输入密码",
          trigger: ["blur", "change"],
        },
        code: {
          required: true,
          message: "请输入验证码",
          trigger: ["blur", "change"],
        },
      },
      btnLoading: false,
      countdown: 0,
      timer: null,
      activeIndex: 1,
      tabS:0,
      agreementChecked: false, 
    };
  },
  created() {
    localStorage.clear();
  },
  destroyed() {
    if (this.timer) {
      clearInterval(this.timer);
    }
  },
  computed: {
    tabMessage() {
      if (this.tabS === 0 && this.activeIndex === 1) {
        return '*如未设置过密码，请点击忘记密码';
      } else if (this.tabS === 0 && this.activeIndex === 2) {
        return '*未注册过手机号请点击下方立即注册';
      } else if (this.tabS === 2) {
        return '*请使用手机号完成分销商注册';
      }else if(this.tabS === 1 && this.activeIndex === 1){
        return '*为了您的账户安全，设置密码前请先进行安全验证';
      }
      return '';
    },
    countdownMessage() {
      return this.countdown > 0 ? `${this.countdown}秒后重试` : '获取验证码';
    },
  },
  methods: {
    ...mapActions("user", ["Login", "FetchUserInfo","SmsLogin","ResetPassword","SmsRegister"]),
    isValidaccountNumber(accountNumber) {
      return /^1[3-9]\d{9}$/.test(accountNumber);
    },
    getVerificationCode() {
      
      if (this.countdown <= 0) {
        this.$refs.form2.validateField('mobile', (errorMessage) => {
          if (!errorMessage) {
            const params = {
              // event: new Date().getTime(),
              event: 'smsLogin',
              mobile: this.form2.mobile,
            };
            Ajax.getSmsCode(params).then(({ error }) => {
              if (error=== 0) {
                this.form.code = '';
                this.$message.success("验证码发送成功");
                this.startCountdown();

              }
            });
          }
        });
        
      }
    },
    getVerificationCode2() {
      const isEmail= this.tabS === 1;
      const eveValue = isEmail ? 'resetPassword' : 'smsRegister';
      if (this.countdown <= 0) {
        this.$refs.form3.validateField('mobile', (errorMessage) => {
          if (!errorMessage) {
            const params = {
              // event: new Date().getTime(),
              event: eveValue,
              mobile: this.form3.mobile,
            };
            Ajax.getSmsCode(params).then(({ error }) => {
              if (error=== 0) {
                this.form3.code = '';
                this.$message.success("验证码发送成功");
                this.startCountdown();

              }
            });
          }
        });
        
      }
    },
    loginTabs(type) {
      this.activeIndex = type;
      this.form= {
        account: "",
        password: "",
      }
      this.form2= {
        mobile: '',
        code: '',
      }
    },
    startCountdown() {
      this.countdown = 60;
      this.timer = setInterval(() => {
        if (this.countdown > 0) {
          this.countdown -= 1;
        } else {
          clearInterval(this.timer);
        }
      }, 1000);
    },
    handleLogin() {
      const isEmailLogin = this.activeIndex === 1;
      const formRef = isEmailLogin ? this.$refs.form : this.$refs.form2;
      const params = isEmailLogin ? { ...this.form } : { ...this.form2 };

      formRef.validate((valid) => {
        if (valid) {
          if (!this.agreementChecked) {
            this.$message.error("请先阅读并同意《用户协议》与《隐私协议》");
            return;
          }

          this.btnLoading = true;
          const loginMethod = isEmailLogin ? this.Login : this.SmsLogin;

          loginMethod(params)
            .then((res) => {
              
              this.$message.success(res.msg);
              // this.$router.push('/mission-hall');
              this.FetchUserInfo();
              
            })
            .then((path) => {
              this.$router.push('/mission-hall');
            })
            .finally(() => {
              this.btnLoading = false;
            });
        }
      });
    },
    handleFormSubmission(action, successMessage) {
      this.$refs.form3.validate((valid) => {
        if (valid) {
          if (!this.agreementChecked) {
            this.$message.error("请先阅读并同意《用户协议》与《隐私协议》");
            return;
          }
          this.btnLoading = true;
          const loginMethod = action==1 ? this.ResetPassword : this.SmsRegister;
          loginMethod(this.form3)
            .then((res) => {
              console.log(res);
              if (res.error === 0) {
                this.$message.success(successMessage);
                this.tabS = 0;
              }
            })
            .finally(() => {
              this.btnLoading = false;
            });
        }
      });
    },

    // confirmLogin() {
    //   this.ResetPassword(this.form3);
    // },

    // Sign_in() {
    //   this.form3.identity = '2';
    //   this.SmsRegister(this.form3);
    // },

    // 调用优化后的方法
    submitConfirmLogin() {
      this.handleFormSubmission(1, "密码修改成功");
    },

    submitSignIn() {
      this.form3.identity = '2';
      this.handleFormSubmission(2, "注册成功");
    },

    Register_now() {
      this.tabS = 2;
      this.activeIndex = 1;
      this.form = {
        account: "",
        password: "",
      };
      this.form2 = {
        mobile: "",
        code: "",
      };
      this.form3 = {
        mobile: '',
        code: '',
        password: '',
      };
    },
  },
};
</script>

<style lang="scss" scoped>
:deep(.ant-form-item) {
  margin-bottom: 36px;

  &:last-child {
    margin-bottom: 0;
  }

  input {
    height: 42px;
    font-size: 18px;
  }
}

:deep(.ant-form-explain) {
  position: absolute;
  top: 48px;
}

.Login-root {
  position: relative;
  width: 100%;
  height: 100%;
  background: rgba(#3c7dff, 0.1) url("~@/assets/img/login/bg.png") no-repeat
    center right;
  background-size: 100% 100%;

  .form-wrap {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    text-align: left;
    width: 1050px;
    height: 672px;
    background: #ffffff;
    border-radius: 40px;
    border: 4px solid #a0d1ff;
    display: flex;
    
    .bg-wrap {
      width: 517px;
      height: 664px;
      img {
        width: 517px;
        height: 664px;
      }
    }
  }
  .login-form {
    padding: 45px 36px 0 40px;
    box-sizing: border-box;
   
    .login-tabs {
      display: flex;
      margin-top: 36px;
      div {
        display: flex;
      }
      p {
        font-weight: 600;
        font-size: 28px;
        color: #999999;
        position: relative;
        cursor: pointer;
        z-index: 10;
        margin: 0;
      }
      
      .loginTabs2 {
        margin-left: 180px;
      }
      p.active, p.activeTabs {
        color: #000000;
      }
      p.active::after {
        content: '';
        display: block;
        width: 112px;
        height: 5px;
        background: #1890FF;
        border-radius: 4px;
        position: absolute;
        bottom: 5px; /* 线条与文字的距离 */
        left: 0;
        z-index: 1;
      }
      p.activeTabs::before {
        content: '';
        display: block;
        width: 56px;
        height: 5px;
        background: #1890FF;
        border-radius: 4px;
        position: absolute;
        bottom: 5px; /* 线条与文字的距离 */
        left: 0;
        z-index: 1;
      }
    }
    .login-tabs-span {
      font-weight: 400;
      font-size: 16px;
      color: #999999;
      margin-top: 6px;
    }
  }
 
  .title {
    img {
      width: 347px;
      height: 35px;
    }
  }

  .form {
    margin-top: 36px;
  }
  .forgot_password {
    margin-top: 20px;
    font-weight: 400;
    font-size: 16px;
    color: #DE443F;
    text-decoration-line: underline;
    
    span {
      cursor: pointer;
    }
  }
  .agreement {
    margin-top: 46px;
    span {
      color: #1890ff;
    }
  }
  .login-btn {
    font-size: 20px;
    margin: 20px auto;
    width: 430px;
    height: 58px;
    background: #1890FF;
    border-radius: 36px;
  }

  .flex {
    display: flex;

    .ant-input-affix-wrapper {
      flex: 1;
    }

    .ant-btn {
      min-width: 110px;
      height: 42px;
      margin-left: 12px;
    }
  }
}
.Register_now {
  width: 100%;
  text-align: center;
  span {
    cursor: pointer;
    font-size: 16px;
   color: #666666;
  }
  
}
</style>
